#!/usr/bin/perl

use strict;
use warnings;
use CGI;
use CGI::Carp qw(fatalsToBrowser); # Remove this in production
use IPC::Run qw(run);

# script to spawn the Xvnc server instance
my $spawnscript = "/usr/local/sbin/spawnXvnc";

# actual URL to be employed
my $urlprefix = "https://x2go-cdm.ing.unimo.it/noVNC/vnc.html?resize=remote&encrypt=1&path=websockify?token=p";#VNCPORT

# webdavcgi url
my $webdavcgiprefix="https://";
my $webdavcgisuffix="x2go-cdm.ing.unimore.it/webdavcgi/";

#-----------------------------------#
#  1. Create a new Perl CGI object  #
#-----------------------------------#

my $cgi = new CGI;


#----------------------------------#
#  2. Print the doctype statement  #
#----------------------------------#

print $cgi->header(
    -expires       => '0',
    -Pragma        => 'no-cache',
    -Cache_Control => join(', ', qw(
        private
        no-cache
        no-store
        must-revalidate
        max-age=0
        pre-check=0
        post-check=0
    )),
);

#----------------------------------------------------#
#  3. Start the HTML doc, and give the page a title  #
#----------------------------------------------------#

print $cgi->start_html('CdM.ing.unimore.it shared terminal server lab');

#--------------------------------------------------------------#
#  4a.  If the program is called without any params, print     #
#  the password_field form.                                    #
#--------------------------------------------------------------#

if (!$cgi->param) {
print $cgi->p('Insert UniMORE credentials, prepending a "<b><tt>n</tt></b>" to fully numerical usernames, e.g.');
	print $cgi->pre("123456\@studenti.unimore.it => n123456");
	print $cgi->pre("pepito\@unimore.it          => pepito");
	print $cgi->start_form;
	print $cgi->start_table;
	print $cgi->Tr(
		$cgi->td('username:'),
		$cgi->td(
			$cgi->textfield(
				-name=>'the_username',
				-value=>'n123456',
				-size=>35,
				-maxlength=>50
			)
		)
	);
	print $cgi->Tr(
		$cgi->td('password:'),
		$cgi->td(
			$cgi->password_field(
				-name=>'the_password',
				-value=>'',
				-size=>35,
				-maxlength=>50
			)
		)
	);
	print $cgi->Tr(
		$cgi->td('share with:'),
		$cgi->td(
			$cgi->textfield(
				-name=>'share_with',
				-value=>'ebertocchi smantova',
				-size=>35,
				-maxlength=>50
			)
		),
		$cgi->td("(optional)")
	);

	# Note: password_field can also take a '-value' parameter,
	#       that can be used as a default value to display.
	#       Using that parameter also, the entry above might look like 
	#	this:
	#
	#print $cgi->password_field(-name=>'the_password',
	#	-value=>'default value',
	#	-size=>35,
	#	-maxlength=>50);
	print $cgi->Tr(
		$cgi->td(''),
		$cgi->td(''
		)
	);
	
	print $cgi->Tr(
		$cgi->td(''),
		$cgi->td(
		$cgi->submit(-value=>'Submit')
	)
	);
	print $cgi->end_table;
	print $cgi->end_form;

} else {

	#----------------------------------------------------------#
	#  4b.  If the program is called with parameters, retrieve #
	#  the 'the_password' parameter, save it in a variable     #
	#  named $yourPassword, and then print it out.             #
	#----------------------------------------------------------#

	#print $cgi->h3('Your credentials are:');
	my ($user)  = $cgi->param('the_username') =~ m/([a-z_][a-z0-9_-]{0,31})/;#($interesting) = $string =~ m/(interesting)/g;
	my ($pass)  = $cgi->param('the_password') =~ m/([[:print:]]+)/;
	my @share   = ( $cgi->param('share_with') =~ m/([a-z_][a-z0-9_-]{0,31})/g);
	#remove any possible occurrence of $user from @share
	my @shareKeepMe = grep { $share[$_] ne $user } 0..$#share;
	@share = @share[@shareKeepMe];
	if ( ( ! $user eq "") and ( ! $pass eq "") ) {
		#print "</BLOCKQUOTE>\n";
		#my $cmd = "sudo " ;
		#$cmd .= "$spawnscript ";
		#$cmd .= "";
		#system($cmd);
		my $in=$pass;
		my ($out,$err);
		# run ['echo', '5900', $user, $cgi->remote_addr()], \$in, \$out, \$err;
		run ['sudo', '/usr/local/sbin/spawnXvnc', $user, $cgi->remote_addr(), @share], \$in, \$out, \$err;
		my $ret=$?; #return code
		$out =~ s/^\s+|\s+$//g;
		if ($ret == 0) {
		    my $url = "$urlprefix$out";
		    ##print "<a href='$url'>$url</a>";
		    print $cgi->p(
			"Remote desktop link:",
		    	$cgi->a({href=>"$url",target=>'_new'},"$url")
		    );
		    print $cgi->p( "You may share it with entitled users.");
		    print $cgi->p( "Messages:");
		    print $cgi->pre( "$err");
		} else {
	
			## was 0DEBUG
			print "<pre><code>";
			print "--- DEBUG --- RETCODE ---\n";
			print "$ret\n";
			print "--- DEBUG ---  STDOUT ---\n";
			print "$out\n";
			print "--- DEBUG ---  STDERR ---\n";
			print "$err\n";
			print "</code></pre>";
		}
	} else {
		print "<pre><code>";
		print "Username or password not syntactically allowed (invalid characters? Empty?).";
		print "Unable to proceed further.";
		print "</code></pre>";
	}

}

#--------------------------------------------------#
#  5. After either case above, end the HTML page.  #
#--------------------------------------------------#
print $cgi->p(
	"File management on the remote machine may be performed by ",
	$cgi->a({href=>"$webdavcgiprefix$webdavcgisuffix",target=>'_new'},"clicking here"),
	"; provide the same credentials if requested."
);


print $cgi->end_html;
